using System.Collections.Generic;
using Tycho.Compiler;
using Tycho.Runtime;

namespace Tycho.Parser {
    internal class ListGenerator : TermGenerator {
        private List<TermAdder> Items;
        public TermGenerator VariableItems;

        public ListGenerator () {
            Items = new List<TermAdder> ();
        }

        public void AddItem (TermGenerator item) {
            Items.Add ((termList, args) => termList.Add(item.BuildTerm (args)));
        }

        public void AddVariableItems (TermGenerator variableItems) {
            Items.Add ((termList, args) => AddAllTerms (termList, args, variableItems));
        }

        private void AddAllTerms (AnyObject termList, AnyObject [] arguments, TermGenerator termGenerator) {
            foreach (var item in termGenerator.BuildTerm (arguments)) {
                termList.Add (item);
            }
        }

        public override AnyObject BuildTerm (params AnyObject [] arguments) {
            AnyObject list = CompilerModule.CreateTermList ();

            foreach (var termAdder in Items) {
                termAdder (list, arguments);
            }

            return list;
        }

        private delegate void TermAdder (AnyObject termList, AnyObject [] arguments);
    }
}